package com.study.shiro.jwt;


import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * https://blog.csdn.net/youanyyou/article/details/78990322?utm_source=blogxgwz2
 *
 * @author: chenhs
 * @date: Created in 15:55 2020/3/5
 **/
public class JWTTest {

    private static final Key KEY = new SecretKeySpec("6MNSobBRCHGIO0fS6MNSobBRCHGIO0fS".getBytes(),
            SignatureAlgorithm.HS512.getJcaName());

    public static void main(String[] args) {
        // String compactJws = generateJwt();
        // validateJwt(compactJws);

        JWKTest jwk = new JWKTest();
        String idToken = jwk.generateToken();

        validateJWK(idToken);

        //System.out.println(System.currentTimeMillis()/1000L + 60);


    }

    /**
     * 注意：header可以不用设置，claims不能和payload同时设置。
     *
     * 这里设置payload
     *
     * @return
     */
    static String generateJwt() {
        System.out.println("*******************生成jwt*********************");
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("type", "1");
        String payload = "{\"user_id\":\"1341137\", \"expire_time\":\"2018-01-01 0:00:00\"}";

        String compactJws = Jwts.builder().setHeader(stringObjectMap)
                .setPayload(payload).signWith(SignatureAlgorithm.HS512, KEY).compact();

        System.out.println("jwt key:" + new String(KEY.getEncoded()));
        System.out.println("jwt payload:" + payload);
        System.out.println("jwt encoded:" + compactJws);
        System.out.println("jwt length:" + compactJws.length());

        return compactJws;
    }


    static void validateJwt(String compactJws) {
        System.out.println("*******************解析jwt*********************");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KEY).parseClaimsJws(compactJws);
        JwsHeader header = claimsJws.getHeader();
        Claims body = claimsJws.getBody();

        System.out.println("jwt header:" + header);
        System.out.println("jwt body:" + body);
        System.out.println("jwt body user-id:" + body.get("user_id", String.class));
    }


    static void validateJWK(String idToken) {

        System.out.println("*******************解析jwk*********************");
        Key abc = new SecretKeySpec("abc".getBytes(), SignatureAlgorithm.HS512.getJcaName());

        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(abc).parseClaimsJws(idToken);
        } catch (Exception e) {
            System.out.println("Token 无效");
            e.printStackTrace();
        }
        JwsHeader header = claimsJws.getHeader();
        Claims body = claimsJws.getBody();

        System.out.println("jwk header:" + header);
        System.out.println("jwk body:" + body);
        System.out.println("jwk body user-id:" + body.get("sub", String.class));


        try {
            Thread.sleep(8000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //校验超时
        if (new Date().after(body.getExpiration())){
            System.out.println("Token 已过期");
        }


    }


}
